package com.xiliubit.cloudpicture.aop;

import com.xiliubit.cloudpicture.annotation.AuthCheck;
import com.xiliubit.cloudpicture.exception.BusinessException;
import com.xiliubit.cloudpicture.exception.ErrorCode;
import com.xiliubit.cloudpicture.exception.ThrowUtils;
import com.xiliubit.cloudpicture.model.entity.User;
import com.xiliubit.cloudpicture.model.enums.UserRoleEnum;
import com.xiliubit.cloudpicture.service.UserService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
public class UserAspect {

    @Resource
    private UserService userService;

    /**
     * 切面，执行拦截
     *
     * @param joinPoint 切点
     * @param authCheck 权限校验
     */
    @Around("@annotation(authCheck)")
    public Object around(ProceedingJoinPoint joinPoint, AuthCheck authCheck) throws Throwable {
        // 获取当前用户
        String mustRole = authCheck.mustRole();
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        User user = userService.getLoginUser(request);
        UserRoleEnum mustRoleEnum = UserRoleEnum.getEnumByValue(mustRole);
        // 权限判断
        // 该方法不需要权限，直接放行
        if (mustRoleEnum == null) {
            return joinPoint.proceed();
        }
        UserRoleEnum userRoleEnum = UserRoleEnum.getEnumByValue(user.getUserRole());
        // 没有登陆，无权限访问
        ThrowUtils.throwIf(userRoleEnum == null, ErrorCode.NOT_LOGIN_ERROR);
        // 该方法需要权限，判断权限
        // 如果是普通用户访问管理员权限，拒绝访问
        if (!mustRoleEnum.equals(userRoleEnum) && UserRoleEnum.User.equals(userRoleEnum)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 通过权限校验
        return joinPoint.proceed();
    }
}
